import requests

from common.logger import GetLogger


class RequestsClient:
    # requests库使用 统一通过session对象 自动管理cookie
    # 类属性  作为全局变量 所有的接口共享session对象
    session = requests.session()
    def __init__(self):
        self.logger = GetLogger.get_logger()
        # 封装底层公共接口调用 需要考虑所有的请求信息
        self.url = None
        self.method = None
        self.headers = None
        self.params = None
        self.json = None
        self.data = None
        self.files = None
        self.resp = None

    def send(self):
        # 发起接口请求前记录日志
        self.logger.info(f'接口url:{self.url}')
        self.logger.info(f'接口的method:{self.method}')
        self.logger.info(f'接口的headers:{self.headers}')
        self.logger.info(f'接口的params:{self.params}')
        self.logger.info(f'接口的json:{self.json}')
        self.logger.info(f'接口的data:{self.data}')
        self.logger.info(f'接口的files:{self.files}')
        try:
            self.resp=RequestsClient.session.request(url=self.url,
                                           method=self.method,
                                           headers=self.headers,
                                           params=self.params,
                                           json=self.json,
                                           data=self.data,
                                           files=self.files)
            # 收集响应信息日志 响应状态码+响应文本信息
            self.logger.info(f'接口响应状态码:{self.resp.status_code}')
            self.logger.info(f'接口响应body信息:{self.resp.text}')
        except BaseException as e:
            self.logger.exception('接口发起错误')
            raise BaseException(f'接口发起错误:{e}')
        return self.resp

# if __name__ == '__main__':
#     client = RequestsClient()
#     client.url = 'http://82.156.74.26:7002/passport/login'
#     client.method = 'post'
#     client.params = {'username': 'mtx0327',
#                       'password': 'fcea920f7412b5da7be0cf42b8c93759',
#                       'captcha': 1512,
#                       'uuid': 'be95c490-6768-11ee-9361-71d25890de14'}
#     resp = client.send()
#     print(resp.status_code)
#     print(resp.json())